package com.definesys.smecrailtransit.module.MonthForm.ViewController;

import android.support.annotation.NonNull;
import android.view.View;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.SmecManager.SmecRealm.RealmManager;
import com.definesys.smecrailtransit.bean.ApplyBean;
import com.definesys.smecrailtransit.bean.LineBean;
import com.definesys.smecrailtransit.bean.StationBean;
import com.definesys.smecrailtransit.databinding.FragmentMonthFormBinding;
import com.definesys.smecrailtransit.module.MonthForm.MonthFormPresenter;
import com.definesys.smecrailtransit.adapter.SelctLineAdapter.SelectLineAdapter;
import com.definesys.smecrailtransit.adapter.SelectUserAdapter.SelectUserAdapter;
import com.definesys.smecrailtransit.module.MonthForm.SendEmailListener;
import com.definesys.smecrailtransit.module.MonthForm.bean.FaultStationBean;
import com.definesys.smecrailtransit.module.MonthForm.bean.MonthFormBean;
import com.definesys.smecrailtransit.module.MonthForm.bean.PositionBean;
import com.definesys.smecrailtransit.module.MonthForm.bean.StatisticBean;
import com.definesys.smecrailtransit.module.MonthForm.dialog.EmailDialog;
import com.definesys.smecrailtransit.utils.CommonUtils;
import com.hwangjr.rxbus.Bus;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnRangeSelectedListener;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


import static android.view.View.GONE;
import static com.prolificinteractive.materialcalendarview.MaterialCalendarView.SELECTION_MODE_RANGE;


/**
 * Created by cjy on 2017/7/27.
 */

public class ViewController {
    private String selectUser;
    private String selectYear;
    private String selectLine;
    public String nowDate;
    private String startDate;
    private String endDate;
    private String popMonth;
    private String eleContractNo;
    private int calendarHeight;
    private String faultType;

    private ArrayList<FaultStationBean> list;
    private ArrayList<PositionBean> popWindowList;
    private ArrayList<ApplyBean> userList;
    private ArrayList<String> lineList;
    private ArrayList<LineBean> lineData;
    private ArrayList<String> popMonthList;
    private ArrayList<StatisticBean> statisticList;

    private FragmentMonthFormBinding fragmentMonthFormBinding;
    private MonthFormPresenter monthFormPresenter;
    protected RealmManager realmManager;
    protected Bus mRxbus;

    private SelectUserAdapter selectUserAdapter;
    private SelectLineAdapter selectLineAdapter;

    private MaterialCalendarView calendar;

    public ViewController(FragmentMonthFormBinding fragmentMonthFormBinding,MonthFormPresenter monthFormPresenter,Bus mRxbus){
        this.fragmentMonthFormBinding = fragmentMonthFormBinding;
        this.monthFormPresenter = monthFormPresenter;
        this.realmManager=RealmManager.getInstance();
        this.mRxbus = mRxbus;

        this.list = new ArrayList<>();
        this.popWindowList = new ArrayList<>();
        this.userList = new ArrayList<>();
        this.lineList = new ArrayList<>();
        this.lineData = new ArrayList<>();
        this.popMonthList = new ArrayList<>();
        this.statisticList = new ArrayList<>();

        this.selectLine = "12号线";
        this.selectUser = "全部运营商";

        this.popMonthList.add("一个月");
        this.popMonthList.add("三个月");
        this.popMonthList.add("半年");
        this.popMonth = "一个月";

        this.faultType = "ALL";

        ApplyBean apply1 = new ApplyBean(-1,"全部运营商");
        this.userList.add(apply1);
        ApplyBean apply2 = new ApplyBean(12299,"上海地铁第四运营有限公司");
        this.userList.add(apply2);
        ApplyBean apply3 = new ApplyBean(12323,"上海地铁第三运营有限公司");
        this.userList.add(apply3);
        ApplyBean apply4 = new ApplyBean(12356,"上海轨道交通十二号线发展有限公司");
        this.userList.add(apply4);

        //设置dialog背景层的点击事件
        fragmentMonthFormBinding.backgroundChoice.setOnClickListener(v -> {
            fragmentMonthFormBinding.choice.setVisibility(View.GONE);
        });
        fragmentMonthFormBinding.backgroundPull.setOnClickListener(v -> {
            fragmentMonthFormBinding.pull.setVisibility(View.GONE);
            fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);

        });
        fragmentMonthFormBinding.line.setOnClickListener(v -> {
            fragmentMonthFormBinding.line.setVisibility(View.GONE);
            fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
        });
        fragmentMonthFormBinding.faultTypePop.setOnClickListener(v -> {
            fragmentMonthFormBinding.faultTypePop.setVisibility(GONE);
            fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
        });

        //日历
        _setCalendar();

        //设置月份下拉列表点击事件
        fragmentMonthFormBinding.choiceMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(fragmentMonthFormBinding.choice.getVisibility() == View.GONE){
                    fragmentMonthFormBinding.choice.setVisibility(View.VISIBLE);
                }else{
                    fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                }
                fragmentMonthFormBinding.line.setVisibility(View.GONE);
                fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
                fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
                fragmentMonthFormBinding.faultTypePop.setVisibility(View.GONE);
                fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
            }
        });

        //设置线路下拉列表点击事件
        fragmentMonthFormBinding.choiceLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectLineAdapter.notifyDataSetChanged();
                if(fragmentMonthFormBinding.line.getVisibility() == View.GONE){
                    fragmentMonthFormBinding.line.setVisibility(View.VISIBLE);
                    fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_top);
                }else{
                    fragmentMonthFormBinding.line.setVisibility(View.GONE);
                    fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
                }
                fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
                fragmentMonthFormBinding.faultTypePop.setVisibility(View.GONE);
                fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
            }
        });

        //设置运营商下拉列表点击事件
        fragmentMonthFormBinding.choiceUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectUserAdapter.select_user = selectUser;
                selectUserAdapter.notifyDataSetChanged();
                fragmentMonthFormBinding.invalidateAll();

                if(fragmentMonthFormBinding.pull.getVisibility() == View.GONE){
                    fragmentMonthFormBinding.pull.setVisibility(View.VISIBLE);
                    fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_top);
                }else{
                    fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                    fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
                }
                fragmentMonthFormBinding.line.setVisibility(View.GONE);
                fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
                fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                fragmentMonthFormBinding.faultTypePop.setVisibility(View.GONE);
                fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
            }
        });

        //设置故障类型下拉列表点击事件
        fragmentMonthFormBinding.faultType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(fragmentMonthFormBinding.faultTypePop.getVisibility() == GONE){
                    fragmentMonthFormBinding.faultTypePop.setVisibility(View.VISIBLE);
                    fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_top);

                    fragmentMonthFormBinding.line.setVisibility(View.GONE);
                    fragmentMonthFormBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
                    fragmentMonthFormBinding.choice.setVisibility(View.GONE);
                    fragmentMonthFormBinding.pull.setVisibility(View.GONE);
                    fragmentMonthFormBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);

                }else{
                    fragmentMonthFormBinding.faultTypePop.setVisibility(View.GONE);
                    fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
                }
            }
        });
        fragmentMonthFormBinding.faultTypeAll.setOnClickListener(v -> {
            fragmentMonthFormBinding.faultTypePop.setVisibility(GONE);
            fragmentMonthFormBinding.faultTypeText.setText("全部故障");
            fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
            ViewController.this.setFaultType("ALL");
            ViewController.this.getNetWorkData();
        });
        fragmentMonthFormBinding.faultTypeSelf.setOnClickListener(v -> {
            fragmentMonthFormBinding.faultTypePop.setVisibility(GONE);
            fragmentMonthFormBinding.faultTypeText.setText("非自身原因停梯");
            fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
            ViewController.this.setFaultType("NOSELF");
            ViewController.this.getNetWorkData();
        });
        fragmentMonthFormBinding.faultTypeStaircase.setOnClickListener(v -> {
            fragmentMonthFormBinding.faultTypePop.setVisibility(GONE);
            fragmentMonthFormBinding.faultTypeText.setText("扶梯故障");
            fragmentMonthFormBinding.faultTypeImg.setBackgroundResource(R.drawable.month_form_bottom);
            ViewController.this.setFaultType("FT");
            ViewController.this.getNetWorkData();
        });


        //邮件发送点击事件
        fragmentMonthFormBinding.email.setOnClickListener(v -> {

            String month;

            if(selectUser.equals("全部运营商")) {
                EmailDialog emailDialog = new EmailDialog(fragmentMonthFormBinding.getRoot().getContext(), R.style.project_back, getNowLineId(lineData), -1, getStartDate(),getEndDate(),
                        new SendEmailListener() {
                            @Override
                            public void sendEmailListener(HashMap<String, Object> map) {
                                monthFormPresenter.sendEmail(map);
                            }
                        });
                emailDialog.show();
            }else {
                EmailDialog emailDialog = new EmailDialog(fragmentMonthFormBinding.getRoot().getContext(), R.style.project_back, getNowLineId(lineData), getNowApplyId(), getStartDate(),getEndDate(),
                        new SendEmailListener() {
                            @Override
                            public void sendEmailListener(HashMap<String, Object> map) {
                                monthFormPresenter.sendEmail(map);
                            }
                        });
                emailDialog.show();
            }
        });

    }



    //获取数据
    public void getNetWorkData(){
        //设置参数
        HashMap<String, String> param = new HashMap<>();
        param.put("from",startDate);
        param.put("to",endDate);
        int l=this.getSelectLine()!=null ? this.getSelectLine().length()-2:0;
        param.put("line",this.getSelectLine().substring(0,l));
        param.put("faultType",this.getFaultType());
        //网络请求
        this.monthFormPresenter.getMonthForm(param);
    }

    //获取本地数据
    public void getLocalData(MonthFormBean data){
        this.lineData = data.getLine();
//        //获取运营商数据
//        this.userList = data.getApply();
//        ApplyBean allApply = new ApplyBean(-1,"全部运营商");
//        this.userList.add(0,allApply);
        //获取统计信息
        this.statisticList = data.getStatistics();

        //获取站点信息
        this.list = data.getStation();
        ArrayList<FaultStationBean> arrayList = new ArrayList<>();
        if(!this.selectUser.equals("全部运营商")){
            for(int i=0 ; i< this.list.size();i++){
                if(this.list.get(i).getApplyId() == this.getNowApplyId()){
                    arrayList.add(this.list.get(i));
                }
            }
            this.list = arrayList;
        }

        //排序处理
        ArrayList<FaultStationBean> dataList = this.list;
        ArrayList<FaultStationBean> resultList = new ArrayList<>();
        int length = this.list.size();
        for(int i = 0; i < length ;i++){

            int min = dataList.get(0).getSeq();
            int index =0;
            for(int j = 0; j < dataList.size() ;j++){
                if(dataList.get(j).getSeq() < min){
                    min = dataList.get(j).getSeq();
                    index = j;
                }
            }
            if(i != 0){
                if(resultList.get(i-1).getSeq() != dataList.get(index).getSeq()-1){
                    FaultStationBean s = new FaultStationBean();
                    s.setSeq(-1);
                    resultList.add(s);
                }
            }
            resultList.add(dataList.get(index));
            dataList.remove(index);
        }

        this.list = resultList;

        fragmentMonthFormBinding.invalidateAll();

    }

    private int getNowLineId(ArrayList<LineBean> lineList){
        if(CommonUtils.notEmpty(lineList)){
            for(int i=0 ;i<lineList.size();i++){
                if(lineList.get(i).getName().equals(this.selectLine)){
                    return lineList.get(i).getLineId();
                }
            }
            return lineList.get(0).getLineId();
        }
        return -1;
    }

    private int getNowApplyId(){
        for(int i=0 ;i<this.userList.size();i++){
            if(this.userList.get(i).getName().equals(this.selectUser)){
                return  this.userList.get(i).getApplyId();
            }
        }
        return this.userList.get(0).getApplyId();
    }

    //获取自动扶梯、升降梯、总计的数量
    public StatisticBean getElevatorNumber(){
        int applyId = getNowApplyId();
        ArrayList<StatisticBean> list = new ArrayList<>();
        if(applyId == -1){
            return this.statisticList.get(0);
        }else{
            for(int i =1 ;i< this.statisticList.size() ; i++){
                if(this.statisticList.get(i).getApplyId() == applyId){
                    return this.statisticList.get(i);
                }
            }
        }
        return this.statisticList.get(0);
    }

    public String getEleContractNo() {
        return eleContractNo;
    }

    public void setEleContractNo(String eleContractNo) {
        this.eleContractNo = eleContractNo;
    }

    //初始化日历插件
    private void _setCalendar(){
        //保存控件高度
        calendarHeight = fragmentMonthFormBinding.calendar.getHeight();

        //获取系统时间
        SimpleDateFormat sDateFormat =  new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //过去七天
        c.setTime(new Date());
        c.add(Calendar.DATE, - 7);
        Date d = c.getTime();

        this.nowDate = sDateFormat.format(new Date());
        this.startDate = sDateFormat.format(d);
        this.endDate = this.nowDate;

        calendar = fragmentMonthFormBinding.calendar;
        calendar.state().edit()
                .setFirstDayOfWeek(Calendar.MONDAY)
                .setMaximumDate(CalendarDay.from(Calendar.getInstance().get(Calendar.YEAR)
                        , Calendar.getInstance().get(Calendar.MONTH)
                        , Calendar.getInstance().get(Calendar.DATE)))
                .setCalendarDisplayMode(CalendarMode.MONTHS)
                .commit();
        calendar.setSelectionMode(SELECTION_MODE_RANGE);
        calendar.setSelectionColor(fragmentMonthFormBinding.getRoot().getContext().getResources().getColor(R.color.calendar_select));
        calendar.setArrowColor(fragmentMonthFormBinding.getRoot().getContext().getResources().getColor(R.color.monthForm_line));
        calendar.setOnRangeSelectedListener(new OnRangeSelectedListener() {
            @Override
            public void onRangeSelected(@NonNull MaterialCalendarView widget, @NonNull List<CalendarDay> dates) {
                startDate = sDateFormat.format(dates.get(0).getDate());
                endDate = sDateFormat.format(dates.get(dates.size()-1).getDate());
                fragmentMonthFormBinding.startDate.setText(startDate);
                fragmentMonthFormBinding.endDate.setText(endDate);
                getNetWorkData();
                //收起动画
//                fragmentMonthFormBinding.getRoot().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //fragmentMonthFormBinding.choice.setVisibility(View.GONE);
//                        //属性动画对象
//                        ValueAnimator va ;
//                        //显示view，高度从height变到0值
//                        va = ValueAnimator.ofInt(calendarHeight,0);
//                        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                            @Override
//                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
//                                //获取当前的height值
//                                int h =(Integer)valueAnimator.getAnimatedValue();
//                                //动态更新view的高度
//                                fragmentMonthFormBinding.choice.getLayoutParams().height = h;
//                                fragmentMonthFormBinding.choice.requestLayout();
//                            }
//                        });
//                        va.setDuration(800);
//                        //开始动画
//                        va.start();
//                    }
//                },300);
                fragmentMonthFormBinding.choice.setVisibility(View.GONE);
            }
        });

    }

    public void selectType(View view){
        switch (view.getId()){
            case R.id.faultTypeAll:
                this.setFaultType("ALL");
                break;
            case R.id.faultTypeSelf:
                this.setFaultType("NOSELF");
                break;
            case R.id.faultTypeStaircase:
                this.setFaultType("FT");
                break;
        }
        this.getNetWorkData();
    }




    //属性 set、get 方法
    public ArrayList<FaultStationBean> getList() {
        return list;
    }

    public void setList(ArrayList<FaultStationBean> list) {
        this.list = list;
    }

    public ArrayList<ApplyBean> getUserList() {
        return userList;
    }

    public void setUserList(ArrayList<ApplyBean> userList) {
        this.userList = userList;
    }

    public String getSelectUser() {
        return selectUser;
    }

    public void setSelectUser(String selectUser) {
        this.selectUser = selectUser;
    }

    public String getSelectLine() {
        return selectLine;
    }

    public void setSelectLine(String selectLine) {
        this.selectLine = selectLine;
    }

    public ArrayList<String> getLineList() {
        return lineList;
    }

    public void setLineList(ArrayList<String> lineList) {
        this.lineList = lineList;
    }

    public FragmentMonthFormBinding getFragmentMonthFormBinding() {
        return fragmentMonthFormBinding;
    }

    public void setFragmentMonthFormBinding(FragmentMonthFormBinding fragmentMonthFormBinding) {
        this.fragmentMonthFormBinding = fragmentMonthFormBinding;
    }

    public ArrayList<PositionBean> getPopWindowList() {
        return popWindowList;
    }

    public void setPopWindowList(ArrayList<PositionBean> popWindowList) {
        this.popWindowList = popWindowList;
    }

    public String getSelectYear() {
        return selectYear;
    }

    public void setSelectYear(String selectYear) {
        this.selectYear = selectYear;
    }

    public SelectUserAdapter getSelectUserAdapter() {
        return selectUserAdapter;
    }

    public void setSelectUserAdapter(SelectUserAdapter selectUserAdapter) {
        this.selectUserAdapter = selectUserAdapter;
    }

    public SelectLineAdapter getSelectLineAdapter() {
        return selectLineAdapter;
    }

    public void setSelectLineAdapter(SelectLineAdapter selectLineAdapter) {
        this.selectLineAdapter = selectLineAdapter;
    }

    public ArrayList<String> getPopMonthList(){
        return this.popMonthList;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getEndDate() {
        return endDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public int getCalendarHeight() {
        return calendarHeight;
    }

    public void setCalendarHeight(int calendarHeight) {
        this.calendarHeight = calendarHeight;
    }

    public String getFaultType() {
        return faultType;
    }

    public void setFaultType(String faultType) {
        this.faultType = faultType;
    }
}
